package com.atguigu.auth.controller;

import com.atguigu.auth.service.SysRoleService;
import com.atguigu.common.config.exception.GuiguException;
import com.atguigu.common.result.Result;
import com.atguigu.model.system.SysRole;
import com.atguigu.vo.system.AssginRoleVo;
import com.atguigu.vo.system.SysRoleQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.PushBuilder;
import javax.validation.constraints.Positive;
import java.util.List;
import java.util.Map;

/**
 * ClassName:SysRoleController
 * Package:com.atguigu.auth.controller
 * Description:
 *
 * @Author:小飞机
 * @Create：2023/5/5 - 8:59
 * @Version: v1.0
 */
@Api(tags = "角色接口管理")
@RestController


@RequestMapping("/admin/system/sysRole")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;
    //查询所用角色 和当前所属的角色

    @ApiOperation("获取角色")
    @GetMapping("/toAssign/{userId}")
    public Result toAssign(@PathVariable Long userId){
        Map<String,Object> map = sysRoleService.findRoleDataById(userId);
        return  Result.ok(map);
    }

    //为用户分配角色
    @ApiOperation("为用户分配角色")
    @PostMapping("doAssign")
    public Result doAssign(@RequestBody AssginRoleVo assginRoleVo){
        sysRoleService.doAssign(assginRoleVo);
        return Result.ok();
    }
    @ApiOperation("查所有角色")
    @GetMapping("/findAll")
    public Result getAll() {
        //调用Service的方法
        List<SysRole> list = sysRoleService.list();
        //模拟异常效果
//        try {
//            int i = 10 /0;
//        }catch (Exception e){
//            throw new GuiguException(2001,"执行自定义的异常");
//        }
        return Result.ok(list);
    }
    //条件分页
    //page 当前页 limit 每页显示的记录数
    // sysRoleQueryVo 条件对象

    @PreAuthorize("hasAuthority('bnt.sysRole.list')")
    @ApiOperation("条件分页")
    @GetMapping("{page}/{limit}")
    public Result pageQueryRole(  @PathVariable long page
                                , @PathVariable long limit
                                , SysRoleQueryVo sysRoleQueryVo) {
        //调用service的方法实现
        //1.创建page对象，传递分页信息
        Page<SysRole> pageParam = new Page<>(page, limit);
        //2.封装条件，判断条件是否为空，不为空就封装
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        String roleName = sysRoleQueryVo.getRoleName();
        if (!StringUtils.isEmpty(roleName)) {
            //封装 like 模糊查询
            wrapper.like(SysRole::getRoleName, roleName);
        }
        //3.调用方法
        IPage<SysRole> pageModel = sysRoleService.page(pageParam, wrapper);
        pageModel.getRecords();
        return Result.ok(pageModel);
    }

    //保存角色
    @PreAuthorize("hasAuthority('bnt.sysRole.add')")
    @ApiOperation("保存角色")
    @PostMapping("save")
    public Result save(@RequestBody SysRole role) {
        //调用server
        boolean isSucceed = sysRoleService.save(role);
        if (isSucceed) {
            return Result.ok();
        }
        return Result.fail();
    }

    //修改角色-根据id
    @PreAuthorize("hasAuthority('bnt.sysRole.list')")
    @ApiOperation("根据id查询")
    @GetMapping("get/{id}")
    public Result get(@PathVariable long id) {
        SysRole sysRole = sysRoleService.getById(id);
        return Result.ok(sysRole);
    }


    //修改角色-修改角色
    @PreAuthorize("hasAuthority('bnt.sysRole.update')")
    @ApiOperation("修改角色")
    @PutMapping("update")
    public Result update(@RequestBody SysRole role) {
        //调用server
        boolean isSuccess = sysRoleService.updateById(role);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

    //根据id删除
    @PreAuthorize("hasAuthority('bnt.sysRole.remove')")
    @ApiOperation("根据id删除")
    @DeleteMapping("remove/{id}")
    public Result deleteById(@PathVariable Long id) {
        boolean isSuccess = sysRoleService.removeById(id);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

    //批量删除
    @PreAuthorize("hasAuthority('bnt.sysRole.remove')")
    @ApiOperation("批量删除")
    @DeleteMapping("batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList) {
        //jsion格式对应关系 [”name“：”luck“ ，”age“：”20“  对应User对象
        //数组格式[1,2,3]  Java的list集合
        boolean isSuccess = sysRoleService.removeByIds(idList);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }
}